#pragma once
#include <pthread.h>
#include <iostream>

namespace MutexModule
{
    class Mutex
    {
    public:
        Mutex()
        {
            pthread_mutex_init(&_mutex, nullptr);
        }

        // 申请锁
        void Lock()
        {
            // pthread_mutex_lock成功返回0，失败返回错误码
            int n = pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                std::cerr << "申请锁失败" << std::endl;
                return;
            }
        }

        // 解锁
        void Unlock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if (n != 0)
            {
                std::cerr << "解锁失败" << std::endl;
                return;
            }
        }

        // 获取锁
        pthread_mutex_t *Get()
        {
            return &_mutex;
        }

        ~Mutex()
        {
            pthread_mutex_destroy(&_mutex);
        }

    private:
        pthread_mutex_t _mutex;
    };

    // 实现RAII风格的互斥锁
    class LockGuard
    {
    public:
        LockGuard(Mutex &mutex)
            : _mutex(mutex)
        {
            _mutex.Lock();
        }

        ~LockGuard()
        {
            _mutex.Unlock();
        }

    private:
        Mutex &_mutex;
    };
}